<template>
  <div>
    <el-table
      :data="splicePortInfoList"
      border
      max-height="300px"
      style="width: 100%"
      @cell-click="cellClick"
    >
      <el-table-column
        type="index"
        :label="$t('SEQUENCE')"
        :width="resetSize(100)"
        align="center"
      />
      <el-table-column
        v-if="type === 'auto'"
        :label="$t('PORTS_USED_NUM')"
        align="center"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.portNumber"
            filterable
            allow-create
            default-first-option
            size="mini"
            @change="selectPortNumChange"
          >
            <el-option
              v-for="item in jointNorms"
              :key="item.value"
              :value="item.value"
              :label="item.value"
              :disabled="isPortNumDisable(item)"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="spliceName" :label="$t('INPORT')">
        <el-table-column prop="inputName" :label="$t('IMPORT_NAME')">
          <template slot-scope="scope">
            <div
              class="select-holder flex"
              :class="
                (scope.row.inputStatus && scope.row.inputStatus !== 'IDLE') ||
                  (scope.row.outputStatus && scope.row.outputStatus !== 'IDLE')
                  ? 'disabled'
                  : ''
              "
            >
              <span class="flex-1" :class="scope.row.inputName ? '' : 'placeholder'">{{
                scope.row.inputName || `${$t("IMPORT_NAME")}`
              }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="inputPort" :label="$t('IMPORT_PORT_NUMBER')">
          <template slot-scope="scope">
            <div
              class="select-holder flex"
              :class="
                (scope.row.inputStatus && scope.row.inputStatus !== 'IDLE') ||
                  (scope.row.outputStatus && scope.row.outputStatus !== 'IDLE')
                  ? 'disabled'
                  : ''
              "
            >
              <span
                class="flex-1"
                :class="scope.row.inputSplicePortName ? '' : 'placeholder'"
              >{{
                scope.row.inputSplicePortName || `${$t("IMPORT_PORT_NUMBER")}`
              }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="number" :label="$t('OUTPORT')">
        <el-table-column prop="outName" :label="$t('EXPORT_NAME')">
          <template slot-scope="scope">
            <div
              class="select-holder flex"
              :class="
                (scope.row.inputStatus && scope.row.inputStatus !== 'IDLE') ||
                  (scope.row.outputStatus && scope.row.outputStatus !== 'IDLE')
                  ? 'disabled'
                  : ''
              "
            >
              <span class="flex-1" :class="scope.row.outputName ? '' : 'placeholder'">{{
                scope.row.outputName || `${$t("EXPORT_NAME")}`
              }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="outPort" :label="$t('EXPORT_PORT_NUMBER')">
          <template slot-scope="scope">
            <div
              class="select-holder flex"
              :class="
                (scope.row.inputStatus && scope.row.inputStatus !== 'IDLE') ||
                  (scope.row.outputStatus && scope.row.outputStatus !== 'IDLE')
                  ? 'disabled'
                  : ''
              "
            >
              <span
                class="flex-1"
                :class="scope.row.outputSplicePortName ? '' : 'placeholder'"
              >{{
                scope.row.outputSplicePortName || `${$t("EXPORT_PORT_NUMBER")}`
              }}</span>
              <i class="el-icon-arrow-down" />
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :label="$t('OPERATE')" class-name="operate-cell" width="80">
        <template v-slot="scope">
          <i
            v-if="scope.$index === splicePortInfoList.length - 1"
            class="el-icon-plus mr-10 icon-font"
            @click="addRow"
          />
          <i
            v-if="
              splicePortInfoList.length > 1 &&
                !(
                  (scope.row.inputStatus && scope.row.inputStatus !== 'IDLE') ||
                  (scope.row.outputStatus && scope.row.outputStatus !== 'IDLE')
                )
            "
            class="el-icon-minus icon-font"
            @click="delRow(scope.row, scope.$index)"
          />
        </template>
      </el-table-column>
    </el-table>

    <div v-show="showSelect" :id="selectId">
      <el-select
        id="select"
        ref="testSelect"
        v-model="activeCurVal.selectVal"
        size="mini"
        @change="selectChange"
        @visible-change="visibleChange"
      >
        <el-option
          v-for="obj in activeList"
          :key="obj.spliceId"
          :label="obj.name"
          :value="obj.spliceId"
          :disabled="isDisable(obj)"
        />
      </el-select>
    </div>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { deepClone } from '@/utils/common'
  export default {
    props: {
      spliceClosure: {
        type: Object,
        default: () => {}
      },
      type: {
        type: String,
        default: 'add'
      },
      selectId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        dialogVisible: false,
        splicePortInfoList: [],
        showSelect: false,
        activeCurVal: {
          selectVal: ''
        },
        activeList: [], // 当前点击选中的列表
        portNumberList: []
      }
    },
    computed: {
      ...mapGetters(['dictList']),
      jointNorms() {
        return this.dictList.JOINT_NORMS
      }
    },
    created() {
      this.initSplicePortInfoList()
    },
    methods: {
      initSplicePortInfoList(type) { // 初始化端口配置列表
        let list = deepClone(this.spliceClosure.splicePortInfoList)
        list = list.sort((a, b) => a.sort - b.sort) || []
        const types = type || this.type
        if (types === 'auto') {
          list = [
            {
              portNumber: '',
              inputSpliceId: '',
              inputSplicePortName: '',
              outputSpliceId: '',
              outputSplicePortName: ''
            }
          ]
        }
        if (types === 'add') {
          list.forEach((i) => {
            i.inputName = ''
            i.outputName = ''
          })
        }
        if (types === 'mod') {
          const { inputList, outputList } = this.spliceClosure
          list.forEach((i) => {
            const inputObj = inputList.find((j) => j.spliceId === i.inputSpliceId)
            const outputObj = outputList.find((j) => j.spliceId === i.outputSpliceId)
            i.inputName = (inputObj && inputObj.spliceName) || ''
            i.outputName = (outputObj && outputObj.spliceName) || ''
          })
        }
        this.splicePortInfoList = list
      },
      cellClick(row, column, cell, event) {
        console.log(row, column)
        // 如果被占用就禁止点击选择
        if (
          (row.inputStatus && row.inputStatus !== 'IDLE') ||
          (row.outputStatus && row.outputStatus !== 'IDLE')
        ) { return }
        this.showSelect = false
        this.activeList = []
        this.activeCurVal = row
        // 点击进口名称
        if (column.property === 'inputName') {
          const list = this.spliceClosure.inputList.map((i) => {
            return {
              ...i,
              name: i.spliceName
            }
          })
          this.updateActiveList(list, row.inputSpliceId, 'inputName', 'inputSpliceId')
        }
        // 点击进口端口号
        if (column.property === 'inputPort') {
          if (!row.inputName) return
          const obj = this.spliceClosure.inputList.find(
            (i) => i.spliceId === row.inputSpliceId
          )
          this.activeCurVal.inputNumber = obj.number
          this.updateActiveList(
            this.setList(obj),
            row.inputSplicePortName,
            'inputSplicePortName'
          )
        }
        // 点击出口名称
        if (column.property === 'outName') {
          const list = this.spliceClosure.outputList.map((i) => {
            return {
              ...i,
              name: i.spliceName
            }
          })
          this.updateActiveList(list, row.outputSpliceId, 'outputName', 'outputSpliceId')
        }
        // 点击出口端口号
        if (column.property === 'outPort') {
          if (!row.outputName) return
          const obj = this.spliceClosure.outputList.find(
            (i) => i.spliceId === row.outputSpliceId
          )
          this.activeCurVal.outputNumber = obj.number
          this.updateActiveList(
            this.setList(obj),
            row.outputSplicePortName,
            'outputSplicePortName'
          )
        }

        if (this.activeList.length === 0 || this.type === 'view') return
        this.$nextTick(() => {
          const selectDiv = document.getElementById(this.selectId)
          const cellbox = cell.querySelector('.select-holder')
          selectDiv.style.top = cellbox.getBoundingClientRect().top + 'px'
          selectDiv.style.left = cellbox.getBoundingClientRect().left + 'px'
          selectDiv.style.width = cellbox.getBoundingClientRect().width + 'px'
          this.$refs.testSelect.toggleMenu()
          this.showSelect = true
          this.$nextTick(() => {
            document.getElementById('select').focus()
          })
        })
      },
      setList(obj) {
        return Array.from(new Array(Number(obj.number)), (i, index) => {
          const name = obj.spliceName + '-' + (index + 1)
          return {
            name: name,
            spliceId: name
          }
        })
      },
      updateActiveList(list, selectval, key1, key2) {
        this.activeList = list
        this.activeCurVal.selectVal = selectval
        this.activeCurVal.key1 = key1
        key2 ? (this.activeCurVal.key2 = key2) : delete this.activeCurVal.key2
      },
      selectChange(val) {
        if (this.activeCurVal.key2) {
          this.activeCurVal[this.activeCurVal.key2] = val
          // 进口名称改变后清空端口号
          if (this.activeCurVal.key2 === 'inputSpliceId') {
            this.activeCurVal.inputSplicePortName = ''
          }
          if (this.activeCurVal.key2 === 'outputSpliceId') {
            this.activeCurVal.outputSplicePortName = ''
          }
        }
        this.$set(
          this.activeCurVal,
          this.activeCurVal.key1,
          this.activeList.find((i) => i.spliceId === val).name
        )
        delete this.activeCurVal.key1
        delete this.activeCurVal.key2
        this.selectBlur()
      },
      visibleChange(data) {
        console.log('visibleChange', data)
        if (data === false) {
          this.selectBlur()
        }
      },
      selectBlur() {
        document.getElementById('select').blur()
        this.$refs.testSelect && this.$refs.testSelect.blur()
        this.$nextTick(() => {
          this.showSelect = false
        })
      },
      isDisable(port) {
        // 判断是否禁用
        const splicePortInfoList = this.splicePortInfoList
        const { name, number } = port
        if (
          this.activeCurVal.key1 === 'inputName' ||
          this.activeCurVal.key1 === 'outputName'
        ) {
          const names = splicePortInfoList.map((i) => i[this.activeCurVal.key1])
          return this.addNumFlag(names, name, number)
        }
        if (
          this.activeCurVal.key1 === 'inputSplicePortName' ||
          this.activeCurVal.key1 === 'outputSplicePortName'
        ) {
          const portNames = splicePortInfoList.map((i) => i[this.activeCurVal.key1])
          if (portNames.includes(name)) {
            return true
          }
        }
        return false
      },
      addNumFlag(names, key, number) {
        let num = 0
        if (names.includes(key)) {
          names.forEach((i) => {
            if (i === key) {
              num++
            }
          })
          if (num >= number) return true
        }
      },
      inputChange(val, index, type) {
        // 进口信息改变后端口配置进口名称修改
        const obj = this.spliceClosure.inputList[index]
        console.log(obj, index)
        this.splicePortInfoList.forEach((i) => {
          if (obj.spliceId === i.inputSpliceId) {
            if (type === 'name') {
              i.inputSplicePortName = i.inputSplicePortName.replace(
                i.inputName,
                obj.spliceName
              )
              i.inputName = obj.spliceName
            } else {
              i.inputSplicePortName = ''
            }
          }
        })
      },
      outputChange(val, index, type) {
        // 出口信息改变后端口配置进口名称修改
        const obj = this.spliceClosure.outputList[index]
        this.splicePortInfoList.forEach((i) => {
          if (obj.spliceId === i.outputSpliceId) {
            if (type === 'name') {
              i.outputSplicePortName = i.outputSplicePortName.replace(
                i.outputName,
                obj.spliceName
              )
              i.outputName = obj.spliceName
            } else {
              i.outputSplicePortName = ''
            }
          }
        })
      },
      addRow() {
        // 端口配置增加
        this.splicePortInfoList.push({
          inputSpliceId: '',
          inputSplicePortName: '',
          outputSpliceId: '',
          outputSplicePortName: ''
        })
      },
      delRow(row, index) {
        this.splicePortInfoList.splice(index, 1)
      },
      selectPortNumChange(val) {
        const maxNum = this.portNumLimit()
        if (val > maxNum) {
          this.$message.error(this.$t('CANNOT_GREATER_THAN'))
        }
      },
      isPortNumDisable(item) {
        // 判断端口数是否可选
        const maxNum = this.portNumLimit()
        if (item.value > maxNum) return true
        return false
      },
      portNumLimit() {
        const inums = this.spliceClosure.inputList.map((i) => i.number)
        const onums = this.spliceClosure.outputList.map((i) => i.number)
        const maxNum = Math.max(...inums, ...onums)
        return maxNum
      }
    }
  }
</script>
<style lang="scss" scoped>
.errinfo {
  font-size: 12px;
  color: #f56c6c;
}
.select-holder.disabled:hover {
  cursor: not-allowed;
}
#selectDivDivergencePort,
#selectPortConfig {
  position: fixed;
  will-change: top, left, width;
  z-index: 2;
}
</style>
